package com.qys.livesMall.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.app.user.constants.AppUserConstant;
import com.qys.livesMall.app.user.model.dto.sys.UserQuery;
import com.qys.livesMall.app.user.model.entity.*;
import com.qys.livesMall.app.user.service.*;
import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.finance.service.FinanceShopAccountService;
import com.qys.livesMall.shop.constants.ShopConstant;
import com.qys.livesMall.shop.mapper.H2ShopBaseMapper;
import com.qys.livesMall.shop.mapper.H2ShopRechargeWithdrawalMapper;
import com.qys.livesMall.shop.mapper.H2ShopStatisticsInfoMapper;
import com.qys.livesMall.shop.mapper.ShopGoodsSkuStocksMapper;
import com.qys.livesMall.shop.modal.entity.ShopStatisticsEveryDay;
import com.qys.livesMall.shop.modal.query.ShopStatisticsQuery;
import com.qys.livesMall.shop.modal.dto.shop.ShopQuery;
import com.qys.livesMall.shop.modal.entity.H2ShopStatisticsInfo;
import com.qys.livesMall.shop.modal.query.QueryShopStatisticsInfo;
import com.qys.livesMall.shop.modal.vo.*;
import com.qys.livesMall.shop.service.H2ShopBaseService;
import com.qys.livesMall.shop.service.H2ShopStatisticsInfoService;
import com.qys.livesMall.shop.service.ShopStatisticsEverydayService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class H2ShopStatisticsInfoServiceImpl extends ServiceImpl<H2ShopStatisticsInfoMapper, H2ShopStatisticsInfo>
        implements H2ShopStatisticsInfoService {
    @Resource
    private H2ShopBaseMapper h2ShopBaseMapper;
    @Resource
    private AppUserRelationService relationService;
    @Resource
    private FinanceShopAccountService financeShopAccountService;
    @Resource
    private IH2AppUserService userService;
    @Resource
    private H2ShopBaseService shopBaseService;
    @Resource
    private UserShopStatisticsService userShopStatistics;
    @Resource
    private ShopStatisticsEverydayService shopStatisticsEverydayService;
    @Resource
    private H2ShopRechargeWithdrawalMapper rechargeWithdrawalMapper;
    @Resource
    private ShopGoodsSkuStocksMapper skuStocksMapper;

    @Autowired
    private IH2AppUserBankService userBankService;
    @Autowired
    private IpOperateStatisticsService ipOperateStatisticsService;


    @Override
    public H2ShopStatisticsInfo getByShopId(Long shopId) {
        LambdaQueryWrapper<H2ShopStatisticsInfo>  wq= Wrappers.lambdaQuery(H2ShopStatisticsInfo.class)
                .eq(H2ShopStatisticsInfo::getShopId, shopId)
                .last("limit 1");
        H2ShopStatisticsInfo info =this.getOne(wq);
        return info;
    }

    @Override
    public H2ShopStatisticsInfo getField(Long shopId,SFunction<H2ShopStatisticsInfo, Object>... functions) {
        LambdaQueryWrapper<H2ShopStatisticsInfo>  wq= Wrappers.lambdaQuery(H2ShopStatisticsInfo.class)
                .select(functions)
                .eq(H2ShopStatisticsInfo::getShopId, shopId)
                .last("limit 1");
        H2ShopStatisticsInfo info =this.getOne(wq);
        return info;
    }

    @Override
    public H2ShopStatisticsInfo getAllField(Long shopId) {
        LambdaQueryWrapper<H2ShopStatisticsInfo>  wq= Wrappers.lambdaQuery(H2ShopStatisticsInfo.class)
                .eq(H2ShopStatisticsInfo::getShopId, shopId)
                .last("limit 1");
        H2ShopStatisticsInfo info =this.getOne(wq);
        return info;
    }

    @Override
    public Page<ShopStatisticsInfoVo> listShopStatisticsInfo(ShopStatisticsQuery query) {
        //如果没有输入任何条件
        if (!query.isExc()){
            Page<ShopStatisticsInfoVo> page = new Page<>(query.getPageNum(), query.getPageSize());
            Page<ShopStatisticsInfoVo> resultPage = h2ShopBaseMapper.getShopBaseInfo(page, null);
            if (CollectionUtils.isEmpty(resultPage.getRecords())) {
                return resultPage;
            }
            //添加其他信息
            return  buildOtherInfo(resultPage);
        }
        //根据用户查询条件查出符合条件的用户id
        List<Long> userIds=null;
        if (StringUtils.isNotBlank(query.getUserDirectPush())){
            //直推
            userIds=relationService.getLowerLevels(query.getUserDirectPush(),1);
        }else if (StringUtils.isNotBlank(query.getUser3rdGeneration())){
            //三代
            List<Integer> levels=new ArrayList<>();
            levels.add(1);
            levels.add(2);
            levels.add(3);
            userIds=relationService.getLowerLevels(query.getUser3rdGeneration(),levels);
        }else if (StringUtils.isNotBlank(query.getUserUnderUmbrella())){
            //伞下
            userIds=relationService.getGreaterLevels(query.getUserUnderUmbrella(),0);
        }
        if (userIds!=null&&userIds.size()==0){
            //条件不符合，直接返回
            return new Page<>(query.getPageNum(), query.getPageSize());
        }


        //构建用户查询条件
        UserQuery userQuery=new UserQuery();

        if (CollectionUtils.isNotEmpty(userIds)){
            //不为空，则添加默认条件 正常状态用户(店铺)，充值用户（店铺），真实用户（店铺）
            query.setShopStatus(ShopConstant.ShopStatus.IN_BUSINESS);
            query.setUserSysType(AppUserConstant.SysUserType.NORMAL);
            query.setSupUserName(null);
            query.setPoxUserName(null);
            userQuery.setUserIds(userIds.stream().map(String::valueOf).collect(Collectors.toList()));
            query.setCharged(Constants.YesNoInt.YES);
        }
        BeanUtils.copyProperties(query,userQuery);
        //用户表查询出符合条件的id
        userQuery.setStartTime(null);
        userQuery.setEndTime(null);
        userQuery.setIp(null);
        userQuery.setPhone(null);
        userIds=userService.getUserIdByQuery(userQuery);
        if (userIds!=null&&userIds.size()==0){
            //条件不符合，直接返回
            return new Page<>(query.getPageNum(), query.getPageSize());
        }
        query.setUserIds(userIds);

        //余额过滤
        if (query.getBalanceStart()!=null||query.getBalanceEnd()!=null) {
            userIds=financeShopAccountService.listByUserIds(userIds, query.getBalanceStart(),query.getBalanceEnd());
            if (userIds!=null&&userIds.size()==0){
                //条件不符合，直接返回
                return new Page<>(query.getPageNum(), query.getPageSize());
            }
            userQuery.setLongUserIds(userIds);
            query.setUserIds(userQuery.getLongUserIds());
        }

        //地址
        if (StringUtils.isNotBlank(query.getBankNo())){
            List<String>strUserIds=null;
            if (CollectionUtils.isNotEmpty(userIds)){
                strUserIds=userIds.stream().map(String::valueOf).collect(Collectors.toList());
            }
            strUserIds=userBankService.listByBankNo(strUserIds,query.getBankNo());
            userQuery.setUserIds(strUserIds);
            query.setUserIds(userQuery.getLongUserIds());
        }



        //上级和代理
        if(StringUtils.isNotBlank(query.getSupUserName())||StringUtils.isNotBlank(query.getPoxUserName())){
            userIds=userShopStatistics.getUserId(userQuery);
            if (userIds!=null&&userIds.size()==0){
                //条件不符合，直接返回
                return new Page<>(query.getPageNum(), query.getPageSize());
            }
            userQuery.setLongUserIds(userIds);
            query.setUserIds(userIds);
        }

        //店铺查询条件
        ShopQuery shopQuery=new ShopQuery();
        BeanUtils.copyProperties(query,shopQuery);
        shopQuery.setApplyIp(query.getIp());
        List<Long> shopIds=shopBaseService.getShopIdByQuery(shopQuery);
        if (shopIds!=null&&shopIds.size()==0){
            //条件不符合，直接返回
            return new Page<>(query.getPageNum(), query.getPageSize());
        }
        query.setShopIds(shopIds);

        //是否充值
        if(query.getCharged()!=null) {
            shopIds = getShopIds(shopIds, Objects.equals(query.getCharged(), Constants.YesNoInt.YES));
            if (CollectionUtils.isEmpty(shopIds)) {
                //条件不符合，直接返回
                return new Page<>(query.getPageNum(), query.getPageSize());
            }
        }
        Page<ShopStatisticsInfoVo> page = new Page<>(query.getPageNum(), query.getPageSize());
        Page<ShopStatisticsInfoVo> resultPage = h2ShopBaseMapper.getShopBaseInfo(page, shopIds);
        if (CollectionUtils.isEmpty(resultPage.getRecords())) {
            return resultPage;
        }
        //添加其他信息
        return  buildOtherInfo(resultPage);
    }

    public Page<ShopStatisticsInfoVo> buildOtherInfo(Page<ShopStatisticsInfoVo> resultPage){
        List<Long> userIds=resultPage.getRecords().stream().map(ShopStatisticsInfoVo::getUserId).collect(Collectors.toList());
        List<String> ips=resultPage.getRecords().stream().map(ShopStatisticsInfoVo::getApplyIp).collect(Collectors.toList());

        //用户信息
        List<H2AppUser> users=userService.getUserOtherInfoByIds(userIds.stream().map(String::valueOf).collect(Collectors.toList()));
        Map<String,H2AppUser> userMap=users.stream().collect(Collectors.toMap(H2AppUser::getId,v->v));
        //每日统计
        List<Long> shopIds=resultPage.getRecords().stream().map(ShopStatisticsInfoVo::getShopId).collect(Collectors.toList());
        List<ShopStatisticsEveryDay> everydays= shopStatisticsEverydayService.getInfoByDate(shopIds, LocalDate.now());
        Map<Long, ShopStatisticsEveryDay> everydayMap=new HashMap<>();
        if (CollectionUtils.isNotEmpty(everydays)){
           everydayMap= everydays.stream().collect(Collectors.toMap(ShopStatisticsEveryDay::getShopId, v->v));
        }
        //ip相关
        List<UserShopStatistics> shopStatistics= userShopStatistics.listByUserIds(userIds);
        Map<Long, UserShopStatistics> shopStatisticsHashMap=new HashMap<>();
        if (CollectionUtils.isNotEmpty(shopStatistics)){
            shopStatisticsHashMap= shopStatistics.stream().collect(Collectors.toMap(UserShopStatistics::getUserId, v->v));
        }
        //钱包地址
        Map<String,H2AppUserBank> bankMap=new HashMap<>();
        List<H2AppUserBank> banks=userBankService.listByUserIds(userIds.stream().map(String::valueOf).collect(Collectors.toList()));
        if (CollectionUtils.isNotEmpty(banks)){
            bankMap=banks.stream().collect(Collectors.toMap(H2AppUserBank::getUserId,v->v,(v1,v2)->v1));
        }
        //ip
        Map<String,Integer> ipMap=new HashMap<>() ;
        if (CollectionUtils.isNotEmpty(ips)) {
            List<IpOperateStatistics> ipList = ipOperateStatisticsService.getbyIps(ips,1);
            if (CollectionUtils.isNotEmpty(ipList)){
                ipMap=ipList.stream().collect(Collectors.toMap(IpOperateStatistics::getIp,IpOperateStatistics::getNum));
            }
        }
        //转换
        for(ShopStatisticsInfoVo vo:resultPage.getRecords()){
            H2AppUser user=userMap.get(vo.getUserId().toString());
            vo.setUserName(user.getUserName());
            vo.setUserRandomId(user.getUserRandomId());
            vo.setSuperiorName(user.getSuperiorName());
            vo.setNickName(user.getNickName());
            ShopStatisticsEveryDay everyday=everydayMap.get(vo.getShopId());
            if (everyday!=null){
                vo.setTodayOrderNum(everyday.getOrderNum());
                vo.setTodayIncome(everyday.getIncome());
            }
            UserShopStatistics statistics=shopStatisticsHashMap.get(vo.getUserId());
            if (statistics!=null) {
                vo.setLastIp(statistics.getFinalOperateIp());
                vo.setLastOperateTime(statistics.getFinalOperateTime());
            }
            H2AppUserBank bank=bankMap.get(String.valueOf(vo.getUserId()));
            if (bank!=null){
                vo.setWalletAddress(bank.getBankNo());
            }
            vo.setSameRegisterIpNum(ipMap.get(vo.getApplyIp()));
        }
        return resultPage;
    }

    private List<Long> getShopIds(List<Long> shopIds,boolean firstCharge){
        LambdaQueryWrapper<H2ShopStatisticsInfo> wq=new LambdaQueryWrapper<>();
        wq.select(H2ShopStatisticsInfo::getShopId);
        if (shopIds!=null) {
            if (shopIds.size()==0){
                shopIds.add(-1l);
            }
            wq.in(H2ShopStatisticsInfo::getShopId,shopIds);
        }
        if (firstCharge){
            wq.isNotNull(H2ShopStatisticsInfo::getFirstCharge);
        }else {
            wq.isNull(H2ShopStatisticsInfo::getFirstCharge);
        }
        List<H2ShopStatisticsInfo> list= list(wq);
        if (list!=null){
            return list.stream().map(H2ShopStatisticsInfo::getShopId).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }


    public List<Long> query(QueryShopStatisticsInfo query){
        boolean exc=false;
        LambdaQueryWrapper<H2ShopStatisticsInfo> wq=new LambdaQueryWrapper<>();
        wq.select(H2ShopStatisticsInfo::getShopId);
        if (query.getShopIds()!=null){
            if (query.getShopIds().size()==0){
                return new ArrayList<>();
            }
            wq.in(H2ShopStatisticsInfo::getShopId,query.getShopIds());
            exc=true;
        }

        if (query.getCharged()!=null) {
            if (query.getCharged()){
                wq.gt(H2ShopStatisticsInfo::getRechargeNumber,0);
            }else {
                wq.eq(H2ShopStatisticsInfo::getRechargeNumber,0);
            }
            exc=true;
        }
        if (query.getWlNumMin()!=null){
            wq.ge(H2ShopStatisticsInfo::getWithdrawalNumber,query.getWlNumMin());
            exc=true;
        }
        if (query.getWlNumMax()!=null){
            wq.le(H2ShopStatisticsInfo::getWithdrawalNumber,query.getWlNumMax());
            exc=true;
        }
        if (!exc){
            return null;
        }
        List<H2ShopStatisticsInfo> list= list(wq);
        if (list!=null){
            return list.stream().map(H2ShopStatisticsInfo::getShopId).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<H2ShopStatisticsInfo> getByShopIds(List<Long> shopIds) {
        LambdaQueryWrapper<H2ShopStatisticsInfo> wq=new LambdaQueryWrapper<>();
        wq.in(H2ShopStatisticsInfo::getShopId,shopIds);
        return list(wq);
    }

    @Override
    public void initData(Long shopId) {

        List<ShopStatisticsEveryDay> shopStatisticsEveryDays= shopStatisticsEverydayService.getAllField(shopId);
        if(CollectionUtils.isEmpty(shopStatisticsEveryDays)){
            return;
        }
        //订单数
        Integer orderNum=0;
        //订单销量
        Integer salesVolume=0;
        //销售额
        BigDecimal salesAmount=BigDecimal.ZERO;
        //充值金额
        BigDecimal reAmount=BigDecimal.ZERO;
        //提现金额
        BigDecimal wlAmount=BigDecimal.ZERO;
        //充值次数
        Integer reNum=0;
        //提现次数
        Integer wlNum=0;
        //收益
        BigDecimal income=BigDecimal.ZERO;
        for (ShopStatisticsEveryDay everyday:shopStatisticsEveryDays){
            orderNum=orderNum+(everyday.getOrderNum()!=null?everyday.getOrderNum():0);
            salesVolume=salesVolume+(everyday.getSalesVolume()!=null?everyday.getSalesVolume():0);
            salesAmount=salesAmount.add(everyday.getSalesAmount()!=null?everyday.getSalesAmount():BigDecimal.ZERO);
            reAmount=reAmount.add(everyday.getReAmount()!=null?everyday.getReAmount():BigDecimal.ZERO);
            wlAmount=wlAmount.add(everyday.getWlAmount()!=null?everyday.getWlAmount():BigDecimal.ZERO);
            reNum=reNum+(everyday.getReNum()!=null?everyday.getReNum():0);
            wlNum=wlNum+(everyday.getWlNum()!=null?everyday.getWlNum():0);
            income=income.add(everyday.getIncome()!=null?everyday.getIncome():BigDecimal.ZERO);
        }
        H2ShopStatisticsInfo shopStatisticsInfo =getAllField(shopId);
        if (shopStatisticsInfo==null){
            shopStatisticsInfo=new H2ShopStatisticsInfo();
        }
        shopStatisticsInfo.setShopId(shopId);
        shopStatisticsInfo.setOrderNumber(orderNum);
        shopStatisticsInfo.setSalesVolume(salesVolume);
        shopStatisticsInfo.setSalesAmount(salesAmount);
        shopStatisticsInfo.setRecharge(reAmount);
        shopStatisticsInfo.setRechargeNumber(reNum);
        shopStatisticsInfo.setWithdrawal(wlAmount);
        shopStatisticsInfo.setWithdrawalNumber(wlNum);
        shopStatisticsInfo.setDifference(reAmount.subtract(wlAmount));
        shopStatisticsInfo.setCumulative(income);

        //首次时间
        if (shopStatisticsInfo.getFirstCharge()==null&&shopStatisticsInfo.getRechargeNumber()>0){
            //获取第一次充值成功的审核时间
            shopStatisticsInfo.setFirstCharge(rechargeWithdrawalMapper.getFirstRechargeDate(shopId));
        }
        if(shopStatisticsInfo.getRechargeNumber()==0){
            shopStatisticsInfo.setFirstCharge(null);
        }
        //复充金额
        if ((shopStatisticsInfo.getRechargeMoney()==null||shopStatisticsInfo.getRechargeMoney().compareTo(BigDecimal.ZERO)==0)&&shopStatisticsInfo.getRechargeNumber()>1){
            shopStatisticsInfo.setRechargeMoney(rechargeWithdrawalMapper.getSecondTimeRechargeAmount(shopId));
        }
        //待提现金额
        shopStatisticsInfo.setWaitWithdrawal(rechargeWithdrawalMapper.getWaitWithdrawalAmount(shopId));
        //库存量 库存额
        Map<String,Object> stock= skuStocksMapper.getStockNumAndAmount(shopId);
        if (stock!=null){
            shopStatisticsInfo.setStocksNum(stock.get("num")!=null?Integer.valueOf(stock.get("num").toString()):0);
            shopStatisticsInfo.setStocksAmount(stock.get("amount")!=null?(BigDecimal) stock.get("amount"):BigDecimal.ZERO);
        }
        saveOrUpdate(shopStatisticsInfo);
    }


}
